package Teacher;

import java.sql.*;

public class Teacher implements TeacherDAO {

    String url = "jdbc:sqlserver://localhost:1433;databaseName=Student_Grade_Management_System;trustServerCertificate=true";
    String user = "ysy";
    String password = "051018";

    private Connection getConnection() throws SQLException {
        return DriverManager.getConnection(url, user, password);
    }

    @Override
    public void insertTeacher(int id, String name, String course) {
        String query = "INSERT INTO 教师 VALUES (?,?,?)";

        try (Connection conn = getConnection();
             PreparedStatement ps = conn.prepareStatement(query)) {

            ps.setInt(1, id);
            ps.setString(2, name);
            ps.setString(3, course);
            ps.executeUpdate();
            System.out.println("插入成功！");

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void updateTeacher(int id, String name, String course) {
        String query = "UPDATE 教师 SET 教师姓名 = ?,课程名=? WHERE 工号 = ?";

        try (Connection conn = getConnection();
             PreparedStatement ps = conn.prepareStatement(query)) {

            ps.setString(1, name);
            ps.setString(2, course);
            ps.setInt(3, id);
            ps.executeUpdate();
            System.out.println("教师信息更新成功！");

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }



    @Override
    public void deleteTeacher(int id) {
        String query = "DELETE FROM 教师 WHERE 工号 = ?";

        try (Connection conn = getConnection();
             PreparedStatement ps = conn.prepareStatement(query)) {

            ps.setInt(1, id);
            ps.executeUpdate();
            System.out.println("教师删除成功！");

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void getTeacher() {
        String sql = "select * from 教师";
        try (Connection conn = getConnection();
             Statement stmt = conn.createStatement()) {
            ResultSet rs = stmt.executeQuery(sql);
            ResultSetMetaData metaData = rs.getMetaData();
            int columnCount = metaData.getColumnCount();
            // 6. 打印列名
            for (int i = 1; i <= columnCount; i++) {
                System.out.print(metaData.getColumnName(i) + "\t");
            }
            System.out.println(); // 换行

            // 7. 打印数据
            while (rs.next()) {
                for (int i = 1; i <= columnCount; i++) {
                    String value = rs.getString(i);
                    System.out.print(value + "\t");
                }
                System.out.println(); // 每行数据输出后换行
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}